from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.decorators import action
from django.shortcuts import get_object_or_404
import subprocess
from .models import City, DataCenter, Host, HostCredential
from .serializers import (
    CitySerializer, DataCenterSerializer,
    HostSerializer, HostCredentialSerializer
)


class CityViewSet(viewsets.ModelViewSet):
    queryset = City.objects.all()
    serializer_class = CitySerializer


class DataCenterViewSet(viewsets.ModelViewSet):
    queryset = DataCenter.objects.all()
    serializer_class = DataCenterSerializer


class HostViewSet(viewsets.ModelViewSet):
    queryset = Host.objects.all()
    serializer_class = HostSerializer

    @action(detail=True, methods=['get'])
    def check_ping(self, request, pk=None):
        host = self.get_object()
        try:
            result = subprocess.run(
                ['ping', '-c', '3', host.ip_address],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                timeout=10
            )
            is_reachable = result.returncode == 0
            return Response({
                'host': host.hostname,
                'ip_address': host.ip_address,
                'is_reachable': is_reachable,
                'output': result.stdout.decode('utf-8')
            })
        except subprocess.TimeoutExpired:
            return Response({
                'host': host.hostname,
                'ip_address': host.ip_address,
                'is_reachable': False,
                'output': 'Ping timed out'
            }, status=status.HTTP_408_REQUEST_TIMEOUT)
        except Exception as e:
            return Response({
                'host': host.hostname,
                'ip_address': host.ip_address,
                'is_reachable': False,
                'error': str(e)
            }, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=True, methods=['get'])
    def credentials(self, request, pk=None):
        host = self.get_object()
        credential = get_object_or_404(HostCredential, host=host)
        serializer = HostCredentialSerializer(credential)
        return Response(serializer.data)


class HostCredentialViewSet(viewsets.ModelViewSet):
    queryset = HostCredential.objects.all()
    serializer_class = HostCredentialSerializer
    http_method_names = ['get', 'patch', 'head', 'options']